<template>
  <transition name="el-fade-in-linear">
    <div class="chat-emoji" :class="{ chatShow: iactive }">
      <!-- <el-dialog :title="name" :visible.sync="chatView" width="800px" custom-class="chatView" :close-on-click-modal="false"> -->
      <div class="usetInfo">
        <div class="chat-title">
          <span>{{ name }}</span>
          <i class="el-icon-close" @click="coloechatShow"></i>
        </div>
        <div class="u_chat" id="chats">
          <!-- <el-scrollbar> -->
          <vue-scrollbar class="my-scrollbar" ref="Scrollbar">
            <ul id="chat_record">
              <li
                :class="['chatCont', { is_active: item.send_id == $g.user_id }]"
                v-for="(item, index) in userChatMessage"
                :key="index"
              >
                <div class="chatCont_txt clear">
                  <span class="chatCont_g box fl">
                    <img :src="BASE_URL + item.send_avatar_path" />
                  </span>
                  <div class="chatCont_bx clear">
                    <div class="chatCont_t box" v-html="item.app_content"></div>
                    <span class="dataTime">{{
                      getDateDiff(item.create_time)
                    }}</span>
                  </div>
                </div>
              </li>
            </ul>
          </vue-scrollbar>
        </div>
        <div class="l_chat">
          <!--   <el-input v-model="chatInput" @keyup.enter.native="sendMessage()" placeholder="输入私信内容…"></el-input>
                      <div class="emoji_ch box">
                          <i class="el-icon-close" @click="closeEmoji" v-if="showEmoji"></i>
                          <img @click="emojiOFF()" src="../../../../public/images/emojim.png" class="emoji_icon">
                          <vueEmoji class="vueEmoji" @select="selectEmoji" v-if="showEmoji"></vueEmoji>
                      </div> -->
          <div id="content" class="txt-content emoji-content"></div>
          <div class="content-count">
            <span v-if="chatLength < 2000"
              ><i class="counts">{{ chatLength }}</i
              ><i> / 2000</i></span
            >
            <span class="forbit" v-else>内容不能超过2000个字符</span>
          </div>
          <el-button
            type="primary"
            :disabled="chatLength > 2000"
            @click="sendMessage()"
            >发送</el-button
          >
        </div>
      </div>
      <!-- </el-dialog> -->
    </div>
  </transition>
</template>
<script>
import E from "wangeditor";
import emotions from "../../../public/emotions.json";
let btnmenu = [
  // 'bold',//粗体
  // 'fontSize',//字号
  // 'fontName',//字体
  // 'italic',//斜体
  // 'undeline',//下划线
  // 'justify',//对齐方式
  "emoticon", //表情
  // 'quote',//引用
  "link", //插入链接
  // 'strikeThrough',//删除线
  "undo", //撤销
  "redo", // 重复
];

import vueEmoji from "./emoji";
import VueScrollbar from "vue2-scrollbar";
require("vue2-scrollbar/dist/style/vue2-scrollbar.css");
export default {
  components: { VueScrollbar, vueEmoji },
  // props: [zxc],
  data() {
    return {
      iactive: false,
      chatInput: "",
      chatInputTXT: "",
      currentUserId: 0,
      userChatList: [],
      userChatMessage: [],
      temp_userChatList: null,
      temp_currentUserId: 0,
      path: null,
      ws: null,
      chatView: true,
      showEmoji: false,
      name: "",
      editor: null,
      chatLength: 0,
    };
  },
  mounted() {
    // console.log(this.show)
    this.$nextTick(function () {
      // 代码保证 this.$el 在 document 中
      this.getUserChatList();
      this.websocket();

      this.editor = new E("#content");

      // 自定义菜单配置
      this.editor.customConfig.menus = btnmenu;
      // 设置超时
      this.editor.customConfig.uploadImgTimeout = 3 * 60 * 1000;
      // 关闭粘贴样式的过滤
      this.editor.customConfig.pasteFilterStyle = false;
      // 忽略粘贴内容中的图片
      this.editor.customConfig.pasteIgnoreImg = true;
      this.editor.customConfig.onfocus = () => {
        // if (this.editor.txt.html() === '<p class="e-placeholder">输入私信内容…</p>') {
        //     this.editor.txt.html('')
        // }
      };

      this.editor.customConfig.onblur = (html) => {
        // console.log( html == '<p><br></p> ')
        // if (html == '<p><br></p>') {
        //     this.editor.txt.html('<p class="e-placeholder">输入私信内容…</p>')
        // }
      };
      this.editor.customConfig.onchange = (html) => {
        this.chatInput = html;
      };
      // 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
      this.editor.customConfig.emotions = [
        {
          // tab 的标题
          title: "默认",
          type: "image",
          content: emotions,
        },
      ];

      this.editor.create();
      // this.editor.txt.html('<p class="e-placeholder">输入私信内容…</p>')
    });
  },
  watch: {
    chatInput: {
      handler() {
        let imgArr = document.querySelectorAll(".w-e-text img");
        let text = "";
        if (this.editor) {
          text = this.editor.txt
            .text()
            .replace(/&nbsp;/g, "")
            .replace(/^\s+|\s+$/g, "");
        }
        this.chatLength = imgArr.length + text.length;
        //    console.log(this.chatLength)
        if (this.chatLength > 2000) {
          this.$message.error("私信内容长度不能超出2000个字符");
          return;
        }
      },
      immediate: true,
    },
  },
  methods: {
    coloechatShow() {
      this.iactive = false;
      this.userChatMessage = [];
      this.editor.txt.html("");
    },
    closeEmoji() {
      this.showEmoji = false;
    },
    selectEmoji(code) {
      // this.showEmoji = false
      this.chatInput += code;
    },
    emojiOFF() {
      this.showEmoji = !this.showEmoji;
    },
    getDateTimeStamp(dateStr) {
      return Date.parse(dateStr.replace(/-/gi, "/"));
    },
    getDateDiff(dateStr) {
      var publishTime = this.getDateTimeStamp(dateStr) / 1000,
        Dseconds,
        Dminutes,
        Dhours,
        Ddays,
        timeNow = parseInt(new Date().getTime() / 1000),
        d,
        date = new Date(publishTime * 1000),
        Y = date.getFullYear(),
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
      //小于10的在前面补0
      if (M < 10) {
        M = "0" + M;
      }
      if (D < 10) {
        D = "0" + D;
      }
      if (H < 10) {
        H = "0" + H;
      }
      if (m < 10) {
        m = "0" + m;
      }
      if (s < 10) {
        s = "0" + s;
      }

      d = timeNow - publishTime;
      Ddays = parseInt(d / 86400);
      Dhours = parseInt(d / 3600);
      Dminutes = parseInt(d / 60);
      Dseconds = parseInt(d);

      if (Ddays > 0 && Ddays < 3) {
        return M + "-" + D + " " + H + ":" + m;
      } else if (Ddays <= 0 && Dhours > 0) {
        return "昨天" + " " + H + ":" + m;
      } else if (Dhours <= 0 && Dminutes > 0) {
        return H + ":" + m;
      } else if (Dseconds < 60) {
        return "刚刚";
        if (Dseconds <= 0) {
          return "";
        } else {
          return "";
        }
      } else if (Ddays >= 3 && Ddays < 30) {
        return M + "-" + D + " " + H + ":" + m;
      } else if (Ddays >= 30) {
        // return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
        return M + "-" + D + " " + H + ":" + m;
      }
    },
    //滚动条
    someMethod() {
      this.$nextTick(function () {
        if (this.currentUserId && document.getElementById("chat_record")) {
          let h = document.getElementById("chat_record").clientHeight;
          this.$refs.Scrollbar.scrollToY(h);
        }
      });
    },
    //聊天记录
    getUserChatList() {
      let success = (res) => {
        let _this = this;
        this.userChatList = deep_clone(res.data);
        this.currentUserId = 0;
        this.temp_userChatList = this.$store.getters.send_userinfo;

        if (this.temp_userChatList != null) {
          let flag = false;
          this.userChatList.forEach(function (item, i) {
            if (item.send_id == _this.temp_userChatList.send_id) {
              flag = true;
              return;
            }
          });
          !flag &&
            this.userChatList.push({
              send_id: this.temp_userChatList.send_id,
              avatar_path: this.temp_userChatList.avatar_path,
              username: this.temp_userChatList.username,
            });

          this.currentUserId = this.temp_userChatList.send_id;
          // _this.getUserChatOne(this.currentUserId);
        }
      };

      this.$ajax({
        url: "/api/user/user_chat_list",
        params: {
          user_id: this.$g.user_id,
        },
        func: {
          success: success,
        },
      });
    },
    //发送信息
    sendMessage() {
      // console.log(this.chatInput)
      let imgArr = document.querySelectorAll(".w-e-text img");
      let len = this.editor.txt
        .text()
        .replace(/&nbsp;/g, "")
        .replace(/^\s+|\s+$/g, "");

      if (imgArr.length == 0 && len.length == 0) {
        this.$message.warning("输入框不能为空");
        return;
      }
      let message = JSON.stringify({
        type: "say",
        to_client_id: this.currentUserId,
        content: this.editor.txt.html(),
      });
      this.showEmoji = false;
      // console.log('发送数据...:', message)
      this.ws.send(message);

      this.chatInput = "";
      this.chatInputTXT = "";
      this.editor.txt.clear();
      this.editor.menus.menus.link._active = false;
    },
    websocket() {
      let webSocketChatURL = sessionStorage.getItem("user_chat_url");
      this.ws = new WebSocket(webSocketChatURL);
      let serverIp = sessionStorage.getItem("host_addr").substring(7, 24);
      this.ws.onopen = () => {
        var message = JSON.stringify({
          type: "login",
          uid: this.$g.user_id == "" ? this.$route.query.id : this.$g.user_id,
          server_ip: serverIp,
        });
        this.ws.send(message);
        // Web Socket 已连接上，使用 send() 方法发送数据
        // console.log('已连接上...,发送身份信息：' + message)
      };
      this.ws.onmessage = (evt) => {
        var data = JSON.parse(evt.data);
        if (data.status == "success") {
          var type = data.type;
          var data = data.data;
          var flag = false;

          // console.log(data[0].send_id, data[0].receive_id, this.currentUserId, type);
          if (type == "send") {
            if (data[0].receive_id == this.currentUserId) {
              // 当前聊天用户，直接追加数组
              this.userChatMessage.push(data[0]);
            }

            this.userChatList.forEach(function (item, i) {
              if (item.send_id == data[0].receive_id) {
                item.content = data[0].content;
                flag = true;
                return;
              }
            });
          } else if (type == "receive") {
            if (data[0].send_id == this.currentUserId) {
              // 当前聊天用户，直接追加数组
              this.userChatMessage.push(data[0]);
            }
            var _this = this;
            this.userChatList.forEach(function (item, i) {
              if (item.send_id == data[0].send_id) {
                item.content = data[0].content;
                if (item.send_id == _this.currentUserId) {
                  item.read_data = "已读";
                } else {
                  item.read_data = "未读";
                }

                flag = true;
                return;
              }
            });
            let message = JSON.stringify({
              type: "read",
              message_id: data[0].id,
            });
            this.ws.send(message);
          } else {
            flag = true;
          }

          this.someMethod();

          if (!flag) {
            this.userChatList.unshift({
              avatar_path: data[0].send_avatar_path,
              content: data[0].content,
              create_time: data[0].create_time,
              //read_data : "未读",
              receive_id: data[0].receive_id,
              send_id: data[0].send_id,
              //sum_data : 26,
              time: data[0].create_time,
              username: data[0].send_name,
            });
          }
        } else if (data.status === "error") {
          //敏感词
          this.$message.warning(data.data);
        }

        console.log("数据已接收...:", data);
      };
      this.ws.onclose = function () {
        // 关闭 websocket
        console.log("连接已关闭...");
      };
      // 组件销毁时调用，中断websocket链接
      this.over = () => {
        this.ws.close();
      };
    },
    getUserChatOne(obj, type) {
      let msg = deep_clone(obj);
      this.chatView = true;
      this.iactive = true;
      if (type == 1) {
        this.name = msg.user_name;
        this.userChatList.forEach(function (item, i) {
          if (item.send_id == msg.user_id) {
            item.read_data = "已读";
            return;
          }
        });

        let success = (res) => {
          let userChatInfo = res.data.filter(
            (item) =>
              (item.send_id === this.$g.user_id &&
                item.receive_id === msg.id) ||
              (item.receive_id === this.$g.user_id && item.send_id === msg.id)
          );
          // console.log(JSON.parse(JSON.stringify(res.data)),msg, 'fdfgdf', JSON.parse(JSON.stringify(userChatInfo)))

          this.userChatMessage = userChatInfo;
          this.currentUserId = this.$store.getters.isMulti
            ? msg.user_id
            : msg.id;
          let message = JSON.stringify({
            type: "allread",
            send_id: this.currentUserId,
            receive_id: this.$g.user_id,
          });
          this.ws.send(message);
          this.someMethod();
        };
        this.$ajax({
          url: "/api/user/user_chat",
          params: {
            sr_1: msg.user_id,
            sr_2: this.$g.user_id,
            update_read: 1,
            orderby: "time",
            orderby_desc: "asc",
            server_ip: location.hostname,
          },
          func: {
            success: success,
          },
        });
      } else {
        this.name = msg.name;
        this.userChatList.forEach(function (item, i) {
          if (item.send_id == msg.id) {
            item.read_data = "已读";
            return;
          }
        });
        let success = (res) => {
          this.userChatMessage = res.data;
          console.log(
            JSON.parse(JSON.stringify(this.userChatMessage)),
            "66666"
          );
          this.currentUserId = msg.id;
          this.someMethod();
        };
        this.$ajax({
          url: "/api/user/user_chat",
          params: {
            sr_1: msg.id,
            sr_2: this.$g.user_id,
            update_read: 1,
            orderby: "time",
            orderby_desc: "asc",
            server_ip: location.hostname,
          },
          func: {
            success: success,
          },
        });
      }
    },
  },
};
</script>

<style lang="scss">
.chat-emoji {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.2);
  visibility: hidden;
  opacity: 0;
  .usetInfo {
    width: 800px;
    position: absolute;
    top: 100px;
    left: 50%;
    margin-left: -400px;
    background: #fff;
    // height: 100%;
  }
  .w-e-text-container
    .w-e-panel-container
    .w-e-panel-tab-content
    .w-e-button-container
    button {
    width: auto;
  }

  .chat-title {
    padding: 20px;
    font-size: 14px;
    color: #fff;
    background: #4c8edc;
    display: flex;
    justify-content: space-between;
    i {
      cursor: pointer;
      font-size: 18px;
      line-height: 0;
    }
  }

  .l_chat {
    text-align: center;
    text-align-last: justify;
    padding: 15px 25px 30px;
    border-top: 1px solid #dddddd;
    position: relative;
    display: flex;
    flex-wrap: row;
    position: relative;
    > div,
    > span > button {
      text-align: left;
      text-align-last: justify;
      display: inline-block;
      vertical-align: top;
    }
    > .el-input {
      width: 600px;
      > input {
        height: 36px;
        line-height: 36px;
      }
    }
    > button {
      padding: 10px 20px;
    }
    .emoji_icon {
      width: 25px;
      height: 25px;
      cursor: pointer;
      margin-top: 4px;
    }
    .txt-content {
      width: 88%;
      height: 100px;
      margin-right: 20px;
      text-align-last: initial;
      .w-e-text-container {
        height: calc(100% - 25px) !important;
      }
      > div {
        background-color: #fff !important;
      }
      img {
        width: 27px;
        height: 27px;
      }
      .w-e-item {
        margin: 6px 6px 0 0;
        padding: 0;
      }
    }
    .content-count {
      position: absolute;
      top: 23px;
      right: 120px;
      .counts {
        color: #999;
      }
      .forbit {
        color: red;
      }
      i:last-child {
        color: #ccc;
      }
    }
  }
  .u_chat {
    height: 520px;
    ul {
      padding: 0 30px;
      > li {
        padding-top: 25px;
      }
    }
  }

  .my-scrollbar {
    height: 100%;
  }
  .chatCont {
    padding-top: 25px;
    &:last-of-type {
      padding-bottom: 25px;
    }
  }
  .chatCont {
    padding-top: 25px;
  }
  .emoji_ch {
    margin: 0 25px;
    .el-icon-close {
      position: absolute;
      z-index: 16;
      color: red;
      font-size: 24px;
      left: 775px;
      top: -215px;
      cursor: pointer;
    }
  }
  .chatCont_txt {
    position: relative;
    > span {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
      background: #fff;
      line-height: 40px;
      text-align: center;
      color: #fff;
      > img {
        width: 100%;
        height: 100%;
      }
    }
    .chatCont_t {
      max-width: 60%;
      padding: 10px 20px;
      font-size: 14px;
      line-height: 21px;
      background: #f8f8f8;
      border-radius: 3px;
      position: relative;
      margin-left: 25px;
      word-wrap: break-word;
      word-break: break-all;
      box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
      &:before {
        content: " ";
        display: inline-block;
        width: 0;
        height: 0;
        overflow: hidden;
        line-height: 0;
        font-size: 0;
        vertical-align: middle;
        border-right: 7px solid #f8f8f8;
        border-left: 0 none;
        border-top: 7px solid transparent;
        border-bottom: 7px solid transparent;
        position: absolute;
        left: -7px;
      }
      img {
        width: 26px;
        height: 26px;
      }
      a {
        color: #348efd;
        text-decoration: underline;
      }
    }
    .dataTime {
      color: #999;
      display: inline-block;
      margin: 10px;
      font-size: 12px;
    }
  }

  .emoji-content {
    .w-e-panel-container {
      top: -264px;
      left: 147px;
      border: 0;
    }
  }

  .is_active {
    .chatCont_txt {
      span {
        float: none;
        float: right;
      }
      .chatCont_t {
        float: none;
        float: right;
        margin: 0 25px 0 0;
        background: #bcdbff;
        word-wrap: break-word;
        word-break: break-all;
        &:before {
          left: initial;
          right: -7px;
          border-left: 7px solid #bcdbff;
          border-right: 0 none;
          border-top: 7px solid transparent;
          border-bottom: 7px solid transparent;
        }
      }
    }
    .chatCont_t {
      border: 0;
      word-wrap: break-word;
      word-break: break-all;
    }
  }
}

.chatShow {
  opacity: 1;
  visibility: visible;
}
</style>
